﻿package ui {
	import flash.display.DisplayObject;
	import flash.display.Graphics;
	import flash.display.Sprite;
	import flash.events.Event;
	public class VBox extends UIContainer {
		public static const LEFT:String = "left";
		public static const RIGHT:String = "right";
		private static const MARGIN:Number = 5;
		private static const SPACE:Number = 0;
		
		public var background:Boolean = false;
		public var autoLabelWidth:Boolean = true;
		
		public var align:String;
		
		public function VBox(options:Object = null) {
			//if (children) {
				//for each (var d:DisplayObject in children) { addChild(d) };
			//}
			
			marginTop = marginLeft = 0;
			
			applyOptions(options);
			
			update();
		}
		
		override public function addChild(child:DisplayObject):DisplayObject {
			var d:DisplayObject = super.addChild(child);
			update();
			return d;
		}
		
		override public function removeChild(child:DisplayObject):DisplayObject {
			var d:DisplayObject = super.removeChild(child);
			update();
			return d;
		}
		
		public function update():void {
			var i:int;
			var d:DisplayObject;
			
			w = 0;
			h = 0;
			/** Label width */
			var lw:Number = 0;
			for (i = 0; i < numChildren; i++) {
				d = getChildAt(i);
				if (d is UIItem) {
					d.x = (d as UIItem).marginLeft;
					h += (d as UIItem).marginTop;
					if (d is TextBox) {
						var labelW:Number = (d as TextBox).labelWidth;
						if (labelW > lw) lw = labelW;
					}
				}
				d.y = h;
				//d.y = i*30;
				h += d.height+SPACE+(d is UIItem ? (d as UIItem).marginBottom : 0);
				if (d.width > w) w = d.width;
			}
			if (autoLabelWidth) {
				for (i = 0; i < numChildren; i++) {
					d = getChildAt(i);
					if (!(d is TextBox)) continue;
					var tb:TextBox = d as TextBox;
					tb.resizeLabel(lw);
				}
			}
			
			if (align == RIGHT) {
				for (i = 0; i < numChildren; i++) {
					d = getChildAt(i);
					d.x = MARGIN+w-d.width;
				}
			}
			
			w += MARGIN*2;
			//h += MARGIN-SPACE;
			
			var g:Graphics = graphics;
			g.clear();
			if (background) {
				g.lineStyle(1, 0x000000, 0.1);
				g.beginFill(0xFFFFFF, 0.9);
				g.drawRoundRect(0, 0, w, h, 6, 6);
			} else {
				g.beginFill(0xFF0000, 0);
				g.drawRect(0, 0, w, h);
			}
			g.endFill();
		}
	}
}